import React, { useRef, useState, useEffect } from 'react';
import {
  DeleteOutlined,
  PlusOutlined,
  ReloadOutlined,
  SettingOutlined,
  EyeOutlined,
  SearchOutlined,
  DownloadOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import {
  VideoMonitorListApi,
  VideoMonitorDeleteApi,
  VideoMonitorBatchDeleteApi,
  VideoMonitorTreeApi,
  VideoMonitorDetailApi,
  VideoMonitorLastPullApi,
  VideoMonitorImport,
  type SysCameraInfo,
} from '@/api/videoMonitorApi';
import type { OperationType } from '@/constants';
import { OperationTypeList } from '@/constants';
import { useRouter } from '@/hooks/useRouter';
import { TableLocalePresets } from '@/utils/tableUtils';
import type { ActionType, ProColumns } from '@ant-design/pro-components';

/**
 * 视频监控管理页面组件
 * 提供视频监控的查看、删除等功能，支持批量操作
 */
const VideoMonitorManager = () => {
  // 路由导航
  const { navigate } = useRouter();

  // 表格操作引用
  const actionRef = useRef<ActionType>(null);

  // 表单实例
  const [form] = AForm.useForm();

  // 抽屉状态管理
  const [drawerShow, setDrawerShow] = useState(false);
  const [drawerType, setDrawerType] = useState<OperationType>('ADD');
  const [currentRecord, setCurrentRecord] = useState<Partial<SysCameraInfo>>({});

  // 表格选择状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 搜索表单状态
  const [searchForm, setSearchForm] = useState({
    keyword: '',
    status: undefined,
    type: undefined,
  });

  // 导入状态
  const [importing, setImporting] = useState(false);

  /**
   * 处理搜索
   */
  const handleSearch = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  /**
   * 获取视频监控列表数据
   * @param params 查询参数
   * @returns 格式化的表格数据
   */
  const fetchData = async (params: Record<string, unknown>) => {
    try {
      // 处理分页参数
      const requestParams = {
        ...params,
        ...searchForm,
        pageNum: params.current,
        pageSize: params.pageSize,
      };

      const res = await VideoMonitorListApi(requestParams);

      if (res.success) {
        const responseData = res.data;

        // 处理不同的响应数据结构
        if (Array.isArray(responseData)) {
          // 如果直接返回数组
          return {
            success: true,
            data: responseData,
            total: responseData.length,
          };
        } else if (responseData && typeof responseData === 'object') {
          // 如果返回对象结构
          const listData = responseData as API.ListType<SysCameraInfo>;
          return {
            success: true,
            data: listData.records ?? [],
            total: listData.total ?? 0,
          };
        }

        return {
          success: true,
          data: [],
          total: 0,
        };
      } else {
        window.$message.error(res.message || '获取视频监控列表失败');
        return {
          success: false,
          data: [],
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取视频监控列表失败:', error);
      window.$message.error('获取视频监控列表失败，请稍后重试');
      return {
        success: false,
        data: [],
        total: 0,
      };
    }
  };

  /**
   * 删除单个视频监控
   * @param record 视频监控记录
   */
  const handleDelete = async (record: SysCameraInfo) => {
    // 参数验证
    if (!record || !record.id) {
      window.$message.error('删除失败：监控ID不存在');
      return;
    }

    const cameraName = record.name || '未知监控';

    AModal.confirm({
      title: '确认删除',
      content: `确定要删除视频监控${cameraName}吗？删除后不可恢复。`,
      okText: '确定删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          const res = await VideoMonitorDeleteApi({ id: String(record.id) });
          if (res.success) {
            window.$message.success('视频监控删除成功');
            actionRef.current?.reload();

            // 如果删除的监控在选中列表中，需要更新选中状态
            if (record.id && selectedRowKeys.includes(record.id)) {
              const newSelectedKeys = selectedRowKeys.filter(key => key !== record.id);
              setSelectedRowKeys(newSelectedKeys);
            }
          } else {
            window.$message.error(res.message || '删除失败');
          }
        } catch (error) {
          console.error('删除视频监控失败:', error);
          window.$message.error('删除失败，请重试');
        }
      },
    });
  };

  /**
   * 批量删除视频监控
   */
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      window.$message.warning('请先选择要删除的视频监控');
      return;
    }

    // 获取有效的监控ID
    const validIds = selectedRowKeys.map(key => String(key)).filter(id => id);

    if (validIds.length === 0) {
      window.$message.error('选中的监控ID无效');
      return;
    }

    AModal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的${validIds.length}个视频监控吗？删除后不可恢复。`,
      okText: '确定删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          const res = await VideoMonitorBatchDeleteApi(validIds);
          if (res.success) {
            window.$message.success(`成功删除 ${validIds.length} 个视频监控`);
            // 清空选中状态
            setSelectedRowKeys([]);
            // 刷新列表
            actionRef.current?.reload();
          } else {
            window.$message.error(res.message || '批量删除失败');
          }
        } catch (error) {
          console.error('批量删除视频监控失败:', error);
          window.$message.error('批量删除失败，请重试');
        }
      },
    });
  };

  /**
   * 查看视频监控详情
   * @param record 视频监控记录
   */
  const handleViewDetail = (record: SysCameraInfo) => {
    if (!record || !record.id) {
      window.$message.error('监控ID不存在，无法查看详情');
      return;
    }

    // 更新最新拉流时间
    VideoMonitorLastPullApi({ id: record.id });

    // 导航到详情页面
    navigate(`/video/monitor/detail?id=${record.id}`);
  };

  /**
   * 处理模板下载
   */
  const handleDownloadTemplate = () => {
    const templateUrl =
      'http://117.176.131.209:8011/%E6%91%84%E5%83%8F%E5%A4%B4%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx';

    // 创建一个临时的 a 标签来触发下载
    const link = document.createElement('a');
    link.href = templateUrl;
    link.download = '摄像头导入模版.xlsx';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    window.$message.success('模板下载已开始');
  };

  /**
   * 处理摄像头导入
   */
  const handleImportCamera = async () => {
    try {
      // 创建一个隐藏的 input 元素
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.xlsx,.xls'; // 只接受 Excel 文件
      input.multiple = false; // 只接受单个文件
      input.style.display = 'none';

      // 监听文件选择事件
      input.onchange = async event => {
        const target = event.target as HTMLInputElement;
        const file = target.files?.[0];

        if (!file) {
          return;
        }

        // 验证文件类型
        const allowedTypes = [
          'application/vnd.ms-excel',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ];

        if (!allowedTypes.includes(file.type)) {
          window.$message.error('只支持 Excel 文件格式(.xls, .xlsx)');
          return;
        }

        // 验证文件大小（限制10MB）
        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
          window.$message.error('文件大小不能超过10MB');
          return;
        }

        try {
          setImporting(true);

          // 创建 FormData 并添加文件
          const formData = new FormData();
          formData.append('file', file);

          // 调用导入 API
          const res = await VideoMonitorImport(formData);

          if (res.success) {
            window.$message.success('摄像头导入成功');
            // 刷新列表数据
            actionRef.current?.reload();
          } else {
            window.$message.error(res.message || '导入失败，请稍后重试');
          }
        } catch (error) {
          console.error('导入摄像头失败:', error);
          window.$message.error('导入失败，请稍后重试');
        } finally {
          setImporting(false);
          // 清理临时创建的 input 元素
          if (input.parentNode) {
            input.parentNode.removeChild(input);
          }
        }
      };

      // 将 input 添加到 DOM 中并触发点击
      document.body.appendChild(input);
      input.click();
    } catch (error) {
      console.error('创建文件选择器失败:', error);
      window.$message.error('操作失败，请稍后重试');
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<SysCameraInfo>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      search: false,
      align: 'center',
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      ellipsis: true,
      search: true,
      align: 'center',
    },
    {
      title: '产品型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      search: true,
      align: 'center',
      valueEnum: {
        0: { text: 'IPcamera' },
        1: { text: 'NVR' },
      },
      render: (_, record) => <span>{record.type === 0 ? 'IPcamera' : 'NVR'}</span>,
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      search: true,
      align: 'center',
      valueEnum: {
        0: { text: '未激活', status: 'default' },
        1: { text: '在线', status: 'success' },
        2: { text: '离线', status: 'error' },
        3: { text: '未知', status: 'warning' },
      },
      render: (_, record) => {
        const statusMap = {
          0: { text: '未激活', color: '#d9d9d9' },
          1: { text: '在线', color: '#52c41a' },
          2: { text: '离线', color: '#f5222d' },
          3: { text: '未知', color: '#faad14' },
        };
        const status = statusMap[record.status || 3];
        return <span style={{ color: status.color, fontWeight: 'bold' }}>{status.text}</span>;
      },
    },
    {
      title: '通道数',
      dataIndex: 'aisleCount',
      key: 'aisleCount',
      width: 100,
      search: false,
      align: 'center',
      render: (_, record) => <span>{record.aisleCount || 1}</span>,
    },
    {
      title: '分组名称',
      dataIndex: 'groupName',
      key: 'groupName',
      width: 120,
      search: true,
      align: 'center',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      search: false,
      align: 'center',
    },
    {
      title: '最近拉流时间',
      dataIndex: 'lastPullFlowTime',
      key: 'lastPullFlowTime',
      width: 180,
      search: false,
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      search: false,
      align: 'center',
      render: (_, record) => (
        <ASpace size="small">
          <a
            href="#"
            onClick={e => {
              e.preventDefault();
              handleViewDetail(record);
            }}
          >
            查看监控
          </a>
          <a
            href="#"
            style={{ marginLeft: '10px' }}
            onClick={e => {
              e.preventDefault();
              handleDelete(record);
            }}
          >
            删除
          </a>
        </ASpace>
      ),
    },
  ];

  // 设备类型选项
  const deviceTypeOptions = [
    { label: 'IPcamera', value: '0' },
    { label: 'NVR', value: '1' },
  ];

  // 设备状态选项
  const deviceStatusOptions = [
    { label: '离线', value: '0' },
    { label: '在线', value: '1' },
  ];

  return (
    <div className="page-wrapper">
      <div className="page-title">
        <div className="page-main-title">视频监控</div>
        <div className="page-sub-title">提供对视频流的播放查看以及转发配置</div>
      </div>

      <div className="page-content-box">
        <div className="page-content flex show-bg">
          <div className="w-full">
            {/* 自定义搜索区域 */}
            <div className="search-area">
              <AForm layout="inline" onFinish={handleSearch}>
                <AForm.Item label="产品型">
                  <ASelect
                    value={searchForm.type}
                    onChange={value => setSearchForm({ ...searchForm, type: value })}
                    options={deviceTypeOptions}
                    style={{ width: '120px' }}
                    allowClear
                    placeholder="请选择"
                  />
                </AForm.Item>
                <AForm.Item label="设备状态">
                  <ASelect
                    value={searchForm.status}
                    onChange={value => setSearchForm({ ...searchForm, status: value })}
                    options={deviceStatusOptions}
                    style={{ width: '120px' }}
                    allowClear
                    placeholder="请选择"
                  />
                </AForm.Item>
                <AForm.Item label="关键词">
                  <AInput
                    value={searchForm.keyword}
                    onChange={e => setSearchForm({ ...searchForm, keyword: e.target.value })}
                    placeholder="请输入设备名称/id/分组名称"
                    style={{ width: '240px' }}
                    allowClear
                  />
                </AForm.Item>
                <AForm.Item>
                  <AButton type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </AButton>
                </AForm.Item>
              </AForm>
            </div>

            <PProTable<SysCameraInfo>
              className="mh-table"
              actionRef={actionRef}
              columns={columns}
              request={fetchData}
              rowKey="id"
              search={false}
              pagination={{
                defaultPageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
              }}
              scroll={{ x: 1000 }}
              size="small"
              options={{
                density: false,
                reloadIcon: (
                  <AButton icon={<ReloadOutlined />} key="reload">
                    刷新
                  </AButton>
                ),
                setting: {
                  draggable: true,
                  checkable: true,
                  showListItemOption: true,
                  settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
                  listsHeight: 400,
                },
              }}
              toolBarRender={() => [
                <AButton
                  key="download-template"
                  icon={<DownloadOutlined />}
                  onClick={handleDownloadTemplate}
                >
                  下载模板
                </AButton>,
                <AButton
                  key="import-camera"
                  icon={<UploadOutlined />}
                  onClick={handleImportCamera}
                  loading={importing}
                  disabled={importing}
                >
                  {importing ? '导入中...' : '导入摄像头'}
                </AButton>,
                <AButton
                  key="batch-delete"
                  icon={<DeleteOutlined />}
                  danger
                  onClick={handleBatchDelete}
                  disabled={selectedRowKeys.length === 0}
                >
                  批量删除{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
                </AButton>,
              ]}
              locale={TableLocalePresets.product(actionRef)}
              tableAlertRender={false} // 隐藏"已选择 X 项"提示
              tableAlertOptionRender={false} // 隐藏"取消选择"等操作按钮
              rowSelection={{
                selectedRowKeys,
                onChange: keys => {
                  setSelectedRowKeys(keys);
                },
                getCheckboxProps: record => ({
                  disabled: false,
                  name: record.name,
                }),
                // 隐藏选择操作按钮
                selections: false,
              }}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default VideoMonitorManager;
